//
//  FaceIDorTouchID.m
//  分享demo
//
//  Created by pc-chtypd056 on 2018/8/10.
//  Copyright © 2018年 CTL. All rights reserved.
//

#import "FaceIDorTouchID.h"
#import <LocalAuthentication/LocalAuthentication.h>

@interface FaceIDorTouchID()

@property (nonatomic, strong) LAContext *lacontext;
/** <#注释说明#> */
@property (nonatomic, strong) UIButton *touchIDBtn;

/** <#注释说明#> */
@property (nonatomic, strong) UILabel *msgLabel;

@end

@implementation FaceIDorTouchID

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self setUpUI];
    }
    return self;
}

- (void)setUpUI{
    
    _touchIDBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _touchIDBtn.frame = CGRectMake(0, 150, ScreenWIDTH, 40);
    [_touchIDBtn setTitle:@"测试按钮" forState:UIControlStateNormal];
    [_touchIDBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _touchIDBtn.tag = 101;
    [_touchIDBtn addTarget:self action:@selector(buttoneEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_touchIDBtn];
    
    _msgLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 200, ScreenWIDTH, 30)];
    _msgLabel.numberOfLines = 0;
    _msgLabel.textAlignment = NSTextAlignmentCenter;
    [self addSubview:_msgLabel];
    
    if (@available(iOS 8.0, *)) {
        self.lacontext = [[LAContext alloc] init];
        
        NSError *authError = nil;
        BOOL isCanEvaluatePolicy = [self.lacontext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&authError];
        
        if (authError) {
            NSLog(@"检测设备是否支持TouchID或者FaceID失败！\n error : == %@",authError.localizedDescription);
            [self showAlertView:[NSString stringWithFormat:@"检测设备是否支持TouchID或者FaceID失败。\n errorCode : %ld\n errorMsg : %@",(long)authError.code, authError.localizedDescription]];
            
        } else {
            if (isCanEvaluatePolicy) {
                // 判断设备支持TouchID还是FaceID
                if (@available(iOS 11.0, *)) {
                    switch (self.lacontext.biometryType) {
                        case LABiometryTypeNone:
                        {
                            [self justSupportBiometricsType:0];
                        }
                            break;
                        case LABiometryTypeTouchID:
                        {
                            [self justSupportBiometricsType:1];
                        }
                            break;
                        case LABiometryTypeFaceID:
                        {
                            [self justSupportBiometricsType:2];
                        }
                            break;
                        default:
                            break;
                    }
                } else {
                    // Fallback on earlier versions
                    NSLog(@"iOS 11之前不需要判断 biometryType");
                    // 因为iPhoneX起始系统版本都已经是iOS11.0，所以iOS11.0系统版本下不需要再去判断是否支持faceID，直接走支持TouchID逻辑即可。
                    [self justSupportBiometricsType:1];
                }
                
            } else {
                [self justSupportBiometricsType:0];
            }
        }
        
    } else {
        // Fallback on earlier versions
        [self justSupportBiometricsType:0];
    }
    
}

- (void)buttoneEvent:(UIButton *)sender{
    
    NSString *myLocalizedReasonString = @"验证";
    
    [self.lacontext evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:myLocalizedReasonString reply:^(BOOL success, NSError * _Nullable error) {
        if (success) {
            NSLog(@"身份验证成功！");
            [self showAlertView:@"验证成功"];
        } else {
            // 做特定的错误判断处理逻辑。
            NSLog(@"身份验证失败！ \nerrorCode : %ld, errorMsg : %@",(long)error.code, error.localizedDescription);
            // error 参考 LAError.h
            [self showAlertView:[NSString stringWithFormat:@"身份验证失败！\nerrCode : %ld\nerrorMsg : %@",(long)error.code, error.localizedDescription]];
        }
    }];
}

// 判断生物识别类型，更新UI
- (void)justSupportBiometricsType:(NSInteger)biometryType
{
    switch (biometryType) {
        case 0:
        {
            NSLog(@"该设备不支持FaceID和TouchID");
            self.msgLabel.text = @"该设备支持不支持FaceID和TouchID";
            self.msgLabel.textColor = [UIColor redColor];
            self.touchIDBtn.enabled = NO;
        }
            break;
        case 1:
        {
            NSLog(@"该设备支持TouchID");
            self.msgLabel.text = @"该设备支持Touch ID";
            [self.touchIDBtn setTitle:@"点击开始验证Touch ID" forState:UIControlStateNormal];
            self.touchIDBtn.enabled = YES;
        }
            break;
        case 2:
        {
            NSLog(@"该设备支持Face ID");
            self.msgLabel.text = @"该设备支持Face ID";
            [self.touchIDBtn setTitle:@"点击开始验证Face ID" forState:UIControlStateNormal];
            self.touchIDBtn.enabled = YES;
        }
            break;
        default:
            break;
    }
}


- (void)showAlertView:(NSString *)msg{
    NSLog(@"msg:%@",msg);
    UIAlertController *alertContrller = [UIAlertController alertControllerWithTitle:nil message:msg preferredStyle:UIAlertControllerStyleAlert];
    if (@available(iOS 8.0, *)) {
        UIAlertAction *okAlertAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil];
        [alertContrller addAction:okAlertAction];
    }else{
        UIAlertAction *okAlertActions = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil];
        [alertContrller addAction:okAlertActions];
    }
    [[Tools getCurrentViewController:self] presentViewController:alertContrller animated:YES completion:nil];
}

@end
